# coding=utf-8
__author__ = 'liubin'

from flask import request
from flask.ext.login import login_required
from flask.ext.restful import Resource, marshal
from project import app, Role, api_view, db
from project.common import tools
from project.forms import RoleForm
from resource import role_resource_fields

class RoleListApi(Resource):
    """
    REST:角色列表
    """
    method_decorators = [login_required]

    def get(self, **kwargs):
        """
        获得角色列表
        :param kwargs:
        :return:
        """
        size = request.args.get('size', None)
        start = request.args.get('start', None)
        draw = request.args.get('draw', '1')
        draw = int(draw)
        data = []
        pager = tools.query_paging(Role.query, size, start)
        for role in pager['query']:
            rowid = 'row_' + str(role.id)
            data_role = {
                'DT_RowId': rowid,
                'DT_RowData': {
                    'pkey': role.id
                },
                'id': role.id,
                'code': role.code,
                'name': role.name
            }
            data.append(marshal(data_role, role_resource_fields))
        return {'success': True, 'draw': draw, 'data': data, 'total': pager['total'], 'page': pager['page'],
            'start': pager['start']}

def post(self, **kwargs):
        """
        追加用户
        :return:
        """
        form = RoleForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            exist_role = Role.query.filter_by(code=form.code.data).first()
            if exist_role is None:
                role = Role(code=form.code.data, name=form.name.data)
                db.session.add(role)
                db.session.commit()
                data_role = {
                    'id': role.id,
                    'code': role.code,
                    'name': role.name
                }
                return {'success': True,  'data': marshal(data_role, role_resource_fields)}
            else:
                messages.append(u'该权限已存在')
                return {'success': False,  'messages': messages}
        else:
            print('error')
            #messages.extend([ error for error in form.errors])
            for error in form.errors:
                for msg in form.errors[error]:
                    messages.append(error + ':' + msg)
            return {'success': False,  'messages': messages}

api_view.add_resource(RoleListApi, '/api/role', endpoint="api_role_list")

class RoleApi(Resource):
    """
    REST: 单个权限
    """
    method_decorators = [login_required]

    def get(self, id, **kwargs):
        """
        获得单个权限
        :param id:
        :param kwargs:
        :return:
        """
        messages = []
        role =  Role.query.filter_by(id=id).first()
        if role:
            data_role = {
                    'id': role.id,
                    'code': role.code,
                    'name': role.name
                }
            return {'success': True,  'data': marshal(data_role, role_resource_fields)}
        else:
            messages.append('指定权限不存在')
            return {'success': False,  'messages': messages}

    def put(self, id, **kwargs):
        """
        更新单个权限
        :param id:
        :param kwargs:
        :return:
        """
        form = RoleForm(csrf_enabled=False)
        messages = []
        if form.validate_on_submit():
            role = Role.query.filter_by(id=id).first()
            if role:
                role.name = form.name.data
                db.session.commit()
                return {'success': True}
            else:
                messages.append('指定权限不存在')
                return {'success': False,  'messages': messages}
        else:
            print('error')
            for error in form.errors:
                for msg in form.errors[error]:
                    messages.append(error + ':' + msg)
            return {'success': False,  'messages': messages}

    def delete(self, id, **kwargs):
        """
        删除权限
        :param id:
        :param kwargs:
        :return:
        """
        messages = []
        role =  Role.query.filter_by(id=id).first()
        if role:
            db.session.delete(role)
            db.session.commit()
            return {'success': True}
        else:
            messages.append('该权限不存在')
            return {'success': False,  'messages': messages}

api_view.add_resource(RoleApi, '/api/role/<int:id>', endpoint="api_role")